package com.lzp.java.annotation.custom.demo;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * 使用注解实现简单的测试异常框架
 * <p>
 * nullcheck抛出异常
 * 异常名称：InvocationTargetException
 * 异常原因：null
 * --------------------------------------
 * div抛出异常
 * 异常名称：InvocationTargetException
 * 异常原因：/ by zero
 * --------------------------------------
 * 一共出现2次异常
 *
 * @author lzp
 * @date 2020/6/8
 */
public class CheckTest {
    public static void main(String[] args) throws IOException {
        // 0. 创建计算器对象
        Calculator c = new Calculator();
        // 1. 获取字节码对象
        Class clazz = c.getClass();
        // 2. 获取所有方法
        Method[] methods = clazz.getMethods();

        int count = 0;
        BufferedWriter bw = new BufferedWriter(new FileWriter("bug.txt"));

        for (Method method : methods) {
            // 3. 如果有注解Check
            if (method.isAnnotationPresent(Check.class)) {
                // 4. 执行
                try {
                    method.invoke(c);
                } catch (Exception e) {
                    count++;
                    bw.write(method.getName() + "抛出异常");
                    bw.newLine();
                    bw.write("异常名称：" + e.getClass().getSimpleName());
                    bw.newLine();
                    bw.write("异常原因：" + e.getCause().getMessage());
                    bw.newLine();
                    bw.write("--------------------------------------");
                    bw.newLine();
                }
            }
        }
        bw.write("一共出现" + count + "次异常");
        bw.flush();
        bw.close();
    }
}
